package justweb

// 请求的封装

import (
	"encoding/json"
	"io"
	"net/http"
)

// 请求的封装
type Context struct {
	W          http.ResponseWriter
	R          *http.Request
	PathParams map[string]string // :param 路径参数的存储
	URLPath    string            //节省一点空间，就不用[]string了
}

// 构造方法
func NewContext(w http.ResponseWriter, r *http.Request) *Context {
	return &Context{
		W:          w,
		R:          r,
		PathParams: make(map[string]string, 1),
		URLPath:    "",
	}
}

// 新建一个Pool中的context
func newContextToPool() *Context {
	return &Context{}
}

func (c *Context)Reset(w http.ResponseWriter, r *http.Request ) {
	c.W = w
	c.R = r
	c.PathParams = make(map[string]string,1)
	c.URLPath = ""
}

// 返回对象
type CommonResponse struct {
	BizCode int         `json:"biz_code"`
	Msg     string      `json:"msg"`
	Data    interface{} `json:"data"`
}

// 从json中读取信息
func (c *Context) ReadJson(data interface{}) error {
	body, err := io.ReadAll(c.R.Body)
	if nil != err {
		return err
	}
	return json.Unmarshal(body, data)
}

// 返回json
func (c *Context) WriteJson(states int, data interface{}) error {
	c.W.WriteHeader(states)
	bs, err := json.Marshal(data)
	if err != nil {
		return err
	}
	_, err = c.W.Write(bs)
	if nil != err {
		return err
	}
	return nil
}

func (c *Context) OkJson(data interface{}) error {
	return c.WriteJson(http.StatusOK, data)
}

func (c *Context) SystemErrJson(data interface{}) error {
	return c.WriteJson(http.StatusInternalServerError, data)
}

func (c *Context) BadRequestJson(data interface{}) error {
	return c.WriteJson(http.StatusBadRequest, data)
}
